package com.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import com.service.UserService;

import com.pojo.User;

@Controller("UserController")
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@Resource
	private Validator validator;
	
	@RequestMapping(value="/index")
	public String index(Model model) {
		model.addAttribute("user", new User());
		return "/jsp/login";
	}
	
	
	@RequestMapping(value="/login")
	public String login(@ModelAttribute User user,BindingResult result, Model model) {
		//this.validator.validate(user, result);
		if(result.hasErrors()) {
			return "/login";
		}
		if(userService.isUsernameExist(user.getUserName())) {
			
			if(userService.isPasswordEqual(user.getUserName(),user.getPassword())) {
				model.addAttribute("userName",user.getUserName());
				model.addAttribute("password",user.getPassword());
				return "../index";
			}else {
				model.addAttribute("PasswordEorr","密码错误");
				return "jsp/login";
			}
		}else {
			model.addAttribute("NameError","用户名不存在");
			return "jsp/login";
		}
	}
	
	
}
